package com.base.data.elasticsearch.repository.support;

import com.base.data.elasticsearch.core.operation.BaseElasticsearchOperations;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.util.Assert;

import java.io.Serializable;


public class BaseElasticsearchRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends
        RepositoryFactoryBeanSupport<T, S, ID> {

    private BaseElasticsearchOperations baseElasticsearchOperations;

    /**
     * Creates a new {@link BaseElasticsearchRepositoryFactoryBean} for the given repository interface.
     *
     * @param repositoryInterface must not be {@literal null}.
     */
    public BaseElasticsearchRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
        super(repositoryInterface);
    }

    /**
     * Configures the {@link BaseElasticsearchOperations} to be used to create Elasticsearch repositories.
     *
     * @param operations the operations to set
     */
    public void setBaseElasticsearchOperations(BaseElasticsearchOperations operations) {

        Assert.notNull(operations, "ElasticsearchOperations must not be null!");

        setMappingContext(operations.getElasticsearchConverter().getMappingContext());
        this.baseElasticsearchOperations = operations;
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport#afterPropertiesSet()
     */
    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        Assert.notNull(baseElasticsearchOperations, "BaseElasticsearchOperations must be configured!");
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory() {
        return new BaseElasticsearchRepositoryFactory(baseElasticsearchOperations);
    }
}
